package com.wichell.framework.wechat.service;

import com.wichell.framework.wechat.contants.WechatContants;
import com.wichell.framework.wechat.exception.WechatMessageException;

public class MessageHandlerImpl implements MessageHandler {

	@Override
	public String handleCustomMessage(String message) throws WechatMessageException {
		String result = "";
		String msgType = getMsgType(message);
		if (WechatContants.MESSAGE_EVENT.equals(msgType)) {
			// 处理事件
			String eventType = getEventType(message);
			result = handleEvent(eventType, message);
		} else {
			// 处理消息
			result = handleMessage(msgType, message);
		}
		return result;
	}

	/**   
	 * @Title: processMessage   
	 * @Description: 根据消息类型处理消息
	 * @param: @param msgType
	 * @param: @param message
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	protected String handleMessage(String msgType, String message) throws WechatMessageException {
		return message;
	}

	/**   
	 * @Title: processMessage   
	 * @Description: 根据消息类型处理消息
	 * @param: @param msgType
	 * @param: @param message
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	protected String handleEvent(String eventType, String message) throws WechatMessageException {
		return message;
	}

	/**   
	 * @Title: getMsgType   
	 * @Description: 简单用正则或者字符串截取获取msgType,不想进行二次转换
	 * @param: @param msgString
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	protected String getMsgType(String msgString) {
		// <MsgType><![CDATA[text]]></MsgType>
		String start = "<MsgType><![CDATA[";
		String end = "]]></MsgType>";
		return msgString.substring(msgString.indexOf(start) + start.length(), msgString.indexOf(end));
	}

	/**   
	 * @Title: getEventType   
	 * @Description: 简单用正则或者字符串截取获取eventType,不想进行二次转换
	 * @param: @param msgString
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	protected String getEventType(String msgString) {
		// <Event><![CDATA[subscribe]]></Event>
		String start = "<Event><![CDATA[";
		String end = "]]></Event>";
		return msgString.substring(msgString.indexOf(start) + start.length(), msgString.indexOf(end));
	}
}
